import { execSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';

// 当前项目根目录
const __dirname = process.cwd();

// code-workspace 文件路径
const workspacePath = path.resolve(__dirname, 'vben-admin.code-workspace');

// 发布脚本源文件路径
const publishPreJsSrc = path.resolve(
  __dirname,
  'scripts',
  'publish',
  'publish-pre.js',
);
const publishShSrc = path.resolve(
  __dirname,
  'scripts',
  'publish',
  'publish.sh',
);

// 读取 workspace 文件
let workspaceContent = fs.readFileSync(workspacePath, 'utf8');
// 处理 JSON 中的尾随逗号（trailing commas）
workspaceContent = workspaceContent
  // 删除数组或对象后多余的逗号（如 },{ 后面的逗号）
  .replaceAll(/(,\s*\})(\s*[}\]])/g, '$2')
  // 删除最后一个元素后的逗号（如 ] 或 } 前的逗号）
  .replaceAll(/,\s*([\]}])/g, '$1');
const workspace = JSON.parse(workspaceContent);

// 过滤出 packages 和 internal 下的目录
const targetPaths = workspace.folders
  .map((folder) => folder.path)
  .filter((p) => p.startsWith('packages/'));

console.log('🎯 检测到以下目标包路径:');
console.log(targetPaths.join('\n'));

// 遍历并执行发布流程
targetPaths.forEach((relativePath) => {
  const fullPath = path.resolve(__dirname, relativePath);
  const packageJsonPath = path.resolve(fullPath, 'package.json');

  // 检查是否存在 package.json
  if (!fs.existsSync(packageJsonPath)) {
    console.warn(`⚠️ 跳过 ${relativePath}：没有找到 package.json`);
    return;
  }

  console.log(`\n📦 正在处理: ${relativePath}`);

  try {
    // 复制 publish-pre.js 和 publish.sh
    fs.copyFileSync(publishPreJsSrc, path.resolve(fullPath, 'publish-pre.js'));
    fs.copyFileSync(publishShSrc, path.resolve(fullPath, 'publish.sh'));

    console.log(`✅ 已复制脚本到 ${relativePath}`);

    // 进入目录并执行脚本
    const cmdPrefix = `cd "${fullPath}" && `;

    console.log(`⏳ 执行 node publish-pre.js`);
    execSync(`${cmdPrefix} node publish-pre.js`, { stdio: 'inherit' });

    console.log(`⏳ 执行 bash publish.sh`);
    execSync(`${cmdPrefix} bash publish.sh`, { stdio: 'inherit' });

    console.log(`✅ 成功发布: ${relativePath}`);
  } catch (error) {
    console.error(`❌ 发布失败: ${relativePath}`, error.message);
  } finally {
    // === 删除脚本 ===
    fs.unlinkSync(path.resolve(fullPath, 'publish-pre.js'));
    fs.unlinkSync(path.resolve(fullPath, 'publish.sh'));
  }
});
